package com.lcz.mytest.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Color;
import android.support.v7.app.ActionBar;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.lcz.mytest.R;
import com.lcz.mytest.db.StockAPI;
import com.lcz.mytest.db.UserService;
import com.lcz.mytest.domain.StockData;
import com.lcz.mytest.domain.User;
import com.lcz.mytest.widget.ToolBarActivity;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;

import net.tsz.afinal.http.AjaxCallBack;

import org.apache.http.Header;

import java.io.IOException;

import pl.droidsonroids.gif.GifDrawable;
import pl.droidsonroids.gif.GifImageView;

/**
 * 实时数据图
 * Created by Administrator on 2016/4/21.
 */
public class PresentStockChartActivity extends ToolBarActivity implements View.OnClickListener {

    private GifImageView gifIv; //显示图表
    private TextView nowPri;    //当前价格
    private TextView nowPic;    //当前价格与今开的差价
    private TextView rate;  //比率
    private TextView todayStartPri; //今开
    private TextView todayMax;  //最高
    private TextView traNumber; //总量
    private TextView yestodEndPri;  //昨收
    private TextView todayMin;  //最低
    private TextView traAmount; //总额
    private StockData.ResultBean.GopictureBean gopicture; //图表集
    private Button minurl;//分时图
    private Button dayurl;//日K线
    private Button weekurl;//周K线
    private Button mouthurl;//月K线
    private StockData stockData;
    private StockData.ResultBean.DataBean data;
    private String stockCode;

    @Override
    protected void findViewById() {
        super.findViewById();
        setContentView(R.layout.activity_szchart);
        gifIv = (GifImageView) findViewById(R.id.giv_gif);
        nowPri = (TextView) findViewById(R.id.nowPri);
        nowPic = (TextView) findViewById(R.id.nowPic);
        rate = (TextView) findViewById(R.id.rate);
        todayStartPri = (TextView) findViewById(R.id.todayStartPri);
        todayMax = (TextView) findViewById(R.id.todayMax);
        traNumber = (TextView) findViewById(R.id.traNumber);
        yestodEndPri = (TextView) findViewById(R.id.yestodEndPri);
        todayMin = (TextView) findViewById(R.id.todayMin);
        traAmount = (TextView) findViewById(R.id.traAmount);
        minurl = (Button) findViewById(R.id.minurl);
        dayurl = (Button) findViewById(R.id.dayurl);
        weekurl = (Button) findViewById(R.id.weekurl);
        mouthurl = (Button) findViewById(R.id.mouthurl);
    }

    @Override
    protected void initView() {
        super.initView();
        minurl.setOnClickListener(this);
        dayurl.setOnClickListener(this);
        weekurl.setOnClickListener(this);
        mouthurl.setOnClickListener(this);
        //股票名称设为导航栏表题
        if (getIntent().getStringExtra("name") != null) {
            getSupportActionBar().setTitle(getIntent().getStringExtra("name"));
        } else {
            getSupportActionBar().setTitle("代码查询");
        }
        //股票编号
        String symbol = getIntent().getStringExtra("symbol");
        stockCode = symbol;
        if (getIntent().getStringExtra("query") != null) {
            symbol = getIntent().getStringExtra("query");
        }
        final Gson gson = new Gson();

        /*final FinalBitmap finalBitmap = FinalBitmap.create(this);
        DisplayMetrics dm = new DisplayMetrics();
        //获取屏幕信息
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        //宽
        final int screenWidth = dm.widthPixels;
        //高
        final int screenHeigh = dm.heightPixels;
        //图片大小
        finalBitmap.configBitmapMaxHeight(screenHeigh / 2);
        finalBitmap.configBitmapMaxWidth(screenWidth);*/

        AjaxCallBack callBack = new AjaxCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                //返回数据
                stockData = gson.fromJson(result, StockData.class);
                //图表集
                gopicture = stockData.getResult().get(0).getGopicture();

                //finalBitmap.display(gifIv, dayurl);
                showChar(gopicture.getDayurl());
                initData(stockData);
            }
        };
        StockAPI.getHS(symbol, callBack);

    }

    public void initData(StockData stockData) {
        //数据集
        data = stockData.getResult().get(0).getData();
        //保留小数
        java.text.DecimalFormat myformat = new java.text.DecimalFormat("0.00");
        nowPri.setText(data.getNowPri());//当前价格
        nowPic.setText(stockData.getResult().get(0).getDapandata().getNowPic());//当前价格与今开的差价
        rate.setText(stockData.getResult().get(0).getDapandata().getRate());//比率
        todayStartPri.setText("今开：" + data.getTodayStartPri());//今开
        yestodEndPri.setText("昨收：" + data.getYestodEndPri());//昨收
        traAmount.setText("总额：" + myformat.format(Double.parseDouble(data.getTraAmount()) / 100000000.0) + "亿");//总额

        SpannableStringBuilder builder = new SpannableStringBuilder("最高：" + data.getTodayMax());
        SpannableStringBuilder builder2 = new SpannableStringBuilder("最低：" + data.getTodayMin());
        SpannableStringBuilder builder3 = new SpannableStringBuilder("总量：" + myformat.format(Double.parseDouble(data.getTraNumber()) / 10000.0) + "万");
        //ForegroundColorSpan 为文字前景色，BackgroundColorSpan为文字背景色
        ForegroundColorSpan redSpan = new ForegroundColorSpan(Color.RED);
        ForegroundColorSpan greenSpan = new ForegroundColorSpan(Color.parseColor("#42bd41"));
        ForegroundColorSpan yellowSpan = new ForegroundColorSpan(Color.parseColor("#ff9800"));

        builder.setSpan(redSpan, 3, data.getTodayMax().length() + 3, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        builder2.setSpan(greenSpan, 3, data.getTodayMin().length() + 3, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        builder3.setSpan(yellowSpan, 3, (myformat.format(Double.parseDouble(data.getTraNumber()) / 10000.0) + "万").length() + 3, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        todayMax.setText(builder);//最高
        todayMin.setText(builder2);//最低
        traNumber.setText(builder3);//总量
        if (Double.parseDouble(data.getNowPri()) > Double.parseDouble(data.getTodayStartPri())) {
            nowPri.setTextColor(Color.parseColor("#aaff0000"));
            nowPic.setTextColor(Color.parseColor("#aaff0000"));
            rate.setTextColor(Color.parseColor("#aaff0000"));
        } else {
            nowPri.setTextColor(Color.parseColor("#42bd41"));
            nowPic.setTextColor(Color.parseColor("#42bd41"));
            rate.setTextColor(Color.parseColor("#42bd41"));
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.minurl://分时图
                showChar(gopicture.getMinurl());
                break;
            case R.id.dayurl://日K线
                showChar(gopicture.getDayurl());
                break;
            case R.id.weekurl://周K线
                showChar(gopicture.getWeekurl());
                break;
            case R.id.mouthurl://月k线
                showChar(gopicture.getMonthurl());
                break;

        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        if (MainActivity.isLogin) {
            menu.add(0, 0, 0, "收藏");
        }
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == 0) {
            new AlertDialog.Builder(this)
                    .setTitle("提示")
                    .setMessage("确认收藏？")
                    .setPositiveButton("确定",
                            new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog,
                                                    int which) {
                                    //将股票代码添加入相应用户的收藏表中
                                    UserService service = new UserService(PresentStockChartActivity.this);
                                    User user = new User();
                                    user.setName(MainActivity.USERNAME);//用户名
                                    user.setStockCode(stockCode);//个股代码
                                    user.setDataType("实时数据");//数据类型
                                    if (service.collect(user)) {
                                        Toast.makeText(PresentStockChartActivity.this, "收藏成功", Toast.LENGTH_SHORT).show();
                                    } else {
                                        Toast.makeText(PresentStockChartActivity.this, "系统出错了，请稍后收藏", Toast.LENGTH_SHORT).show();
                                    }
                                }

                            }).setNegativeButton("取消", null).show();
        }
        return super.onOptionsItemSelected(item);
    }

    //finalBitmap显示图片过小，故使用asyncHttpClient和GifDrawable加载显示
    public void showChar(String url) {
        new AsyncHttpClient().get(url, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int i, Header[] headers, byte[] bytes) {
                try {
                    GifDrawable gifDrawable = new GifDrawable(bytes);
                    gifIv.setBackgroundDrawable(gifDrawable);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
                Toast.makeText(PresentStockChartActivity.this, "资源加载失败，稍后再试！", Toast.LENGTH_SHORT).show();
            }
        });
    }
}
